package cn.com.ejiakanghu.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.task.Task;
import org.linlinjava.litemall.core.util.BeanUtil;
import org.linlinjava.litemall.db.domain.LitemallOrderItem;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.util.OrderUtil;

import java.time.LocalDateTime;

public class OrderUnconfirmTask extends Task {
    private final Log logger = LogFactory.getLog(OrderUnconfirmTask.class);
    /**
     * 子订单id
     */
    private int orderId = -1;

    public OrderUnconfirmTask(Integer orderId, long delayInMilliseconds){
        super("OrderUnpaidTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
    }

    public OrderUnconfirmTask(Integer orderId){
        super("OrderUnpaidTask-" + orderId, SystemConfig.getOrderUnconfirm() * 60 * 1000);
        this.orderId = orderId;
    }

    @Override
    public void run() {
        logger.info("系统开始处理延时任务---订单超时未确认---" + this.orderId);

        LitemallOrderService orderService = BeanUtil.getBean(LitemallOrderService.class);

        LitemallOrderItem orderItem = orderService.findItemById(this.orderId);
        if(orderItem == null){
            return;
        }
        if(!OrderUtil.STATUS_SHIP.equals(orderItem.getOrderStatus()) && !OrderUtil.STATUS_SHIP_SELF.equals(orderItem.getOrderStatus())){
            return;
        }

        orderItem.setOrderStatus(OrderUtil.STATUS_AUTO_CONFIRM);
        orderItem.setFinishTime(LocalDateTime.now());
        orderItem.setConfirmTime(LocalDateTime.now());
        if (orderService.updateItemWithOptimisticLocker(orderItem) == 0) {
            logger.info("订单 ID=" + orderItem.getId() + " 数据已经更新，放弃自动确认收货");
        } else {
            logger.info("订单 ID=" + orderItem.getId() + " 已经自动确认收货");
        }
        orderService.saveSettle(orderItem, null);
        orderService.saveDeduct(orderItem);

        logger.info("系统结束处理延时任务---订单超时未确认---" + this.orderId);
    }
}
